<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="170px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-row>
        <el-col :span="11">
          <el-form-item label="所属机构" prop="deptId">
            <el-select
              v-model="ruleForm.deptId"
              :disabled="ifSchoolId"
              placeholder="请选择机构"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in schoolList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="餐品名称:" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入餐品名称" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="餐品类别:" prop="classId">
            <el-select clearable v-model="ruleForm.classId" placeholder="请输入餐品类别" size="mini">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,index) in classData"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="餐品单位:" prop="unit">
            <el-input v-model="ruleForm.unit" placeholder="请输入餐品单位" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="11">
          <el-form-item label="餐品价格（学生）:" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请输入餐品价格" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="餐品价格（老师）:" prop="discPrice">
            <el-input v-model="ruleForm.discPrice" placeholder="请输入餐品价格" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="24">
          <el-form-item label="餐品照片:" >
            上传图片
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button @click="resetForm('ruleForm')">{{$t("action.reset")}}</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{$t("action.save")}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import ethnic from "@/assets/json/ethnic.js";
import { format } from "@/utils/datetime";

export default {
  name: "edit",
  props: {
    msg: ""
  },
  data() {
    return {
      url: this.$Config.url,
      ethnicList: [], //名族列表
      schoolList: [], //机构列表
      gradeData: [], //年级列表
      classData: [], //班级列表
      id: "", //修改对应的id
      ifSchoolId: false,
      ruleForm: {
        name: "", //餐品名称
        classId: "", //餐品类别
        unit:"",//餐品单位
        price:"",//学生价格
        deptId:"",//所属机构
        discPrice:"",//老师价格
      },
      rules: {
        name: [
          { required: true, message: "请输入餐品名称", trigger: "blur" },
        ],
        classId: [{ required: true, message: "请选择餐品类别", trigger: "change" }],
        unit: [{ required: true, message: "请输入餐品单位", trigger: "blur" }],
        deptId:[{ required: true, message: "请选择所属机构", trigger: "change" }],
        price: [{ required: true, message: "请输入餐品价格（学生）", trigger: "blur" }],
        discPrice: [{ required: true, message: "请输入餐品价格（老师）", trigger: "blur" }]
      },
      formData: {}
    };
  },
  mounted() {
    this.ethnicList = ethnic;
    this.getSchool();
    this.schoolId();
    this.getClassId();
  },
  methods: {
    getClassId(){
      const that = this;
      this.$axios
        .get(that.url + "/admin/productclass/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.classData = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    schoolId() {
      try {
        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
        if (deptId == null || deptId == "") {
          this.ifSchoolId = false;
          this.ruleForm.deptId='';
        } else {
          this.ifSchoolId = true;//不能点击
        }

        this.ruleForm.deptId = deptId;
      } catch (error) {}
    },
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetData(id = 1) {
      this.$refs["ruleForm"].resetFields();//先清空
      const that = this;
      const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
      this.schoolId();

      if (id) {
        this.id = id;
      }
      this.$axios
        .get(that.url + "/admin/product/get/{id}", {
          params: {
            id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.status == 200) {
            let data = res.data.data;
            that.ruleForm = {
              name: res.data.data.name, //餐品名称
              classId:  res.data.data.classId, //餐品类别
              unit:res.data.data.unit,//餐品单位
              price:res.data.data.price,//学生价格
              deptId:res.data.data.deptId,//所属机构
              discPrice:res.data.data.discPrice,//老师价格
            };
            that.id = data.id;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          that.send();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    send() {
      const that = this;
      const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
      const data={
        id: this.id,
        classId:this.ruleForm.classId,
        deptId:deptId||this.ruleForm.deptId,
        discPrice:this.ruleForm.discPrice,
        name:this.ruleForm.name,
        price:this.ruleForm.price,
        unit:this.ruleForm.unit,
        url:"http://images.gshxkj.com.cn/index/banner8.png"
      }
      this.$axios
        .post(
          that.url + "/admin/product/save",
          that.$qs.stringify(data),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.status == 200) {
            if(res.data.code==200){
              if (that.msg == 1) {
                that.$message({
                  message: "添加成功",
                  type: "success"
                });
              } else {
                that.$message({
                  message:"修改成功",
                  type: "success"
                });
              }
              that.$emit("hideEdit", false);
            }else{
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.id="";
      this.schoolId();
    }
  }
};
</script>

<style scoped lang="scss">
.el-select,
.el-date-editor {
  width: 100%;
}
</style>
